﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.Web.UI.WebControls;
using Grauers_set_metadata_properties.Grauers;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI.HtmlControls;

namespace Grauers_set_metadata_properties.Layouts.Grauers_set_metadata_properties
{
    public partial class GrauersMetadataPropertiesSettings : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                addImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/Grauers/add.png";
                updateImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/Grauers/save.png";
                cancelImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/Grauers/cancel.png";
                bindDocumentLibraries();
                bindRepeater();
            }
        }



        protected void addImageButton_Click(object sender, EventArgs e)
        {
            DocumentPropertyItem dpi = new DocumentPropertyItem();
            
            dpi.Library = DocumentsDropDownList.SelectedValue;
            dpi.Issue = IssueDropDownList.SelectedValue;
            dpi.ApprovedBy = ApprovedByDropDownList.SelectedValue;
            dpi.ApprovedDate = ApprovedDateDropDownList.SelectedValue;

            // Check if already exist!
            List<DocumentPropertyItem> dpiList = DocumentPropertyBusinessLayer.GetAll();
            if (dpiList.FindLast(x => x.Library == dpi.Library) == null)
            {

                SPList list = SPContext.Current.Web.Lists[dpi.Library];
                if (list != null)
                {
                    bool found = false;
                    foreach (SPEventReceiverDefinition er in list.EventReceivers)
                    {
                        if (er.Class == "Grauers_set_metadata_properties.Grauers_metadata_properties_handler.Grauers_metadata_properties_handler")
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {

                        #region Add to EventReceiver

                        #region Updated
                        SPEventReceiverDefinition erd = list.EventReceivers.Add();
                        erd.Assembly = Assembly.GetExecutingAssembly().FullName;
                        erd.Class = "Grauers_set_metadata_properties.Grauers_metadata_properties_handler.Grauers_metadata_properties_handler";
                        erd.SequenceNumber = 1000;
                        erd.Type = SPEventReceiverType.ItemUpdated;
                        erd.HostId = list.ID;
                        erd.HostType = SPEventHostType.List;
                        erd.Synchronization = SPEventReceiverSynchronization.Synchronous;
                        erd.Update();
                        #endregion

                        #region Checked in
                        erd = list.EventReceivers.Add();
                        erd.Assembly = Assembly.GetExecutingAssembly().FullName;
                        erd.Class = "Grauers_set_metadata_properties.Grauers_metadata_properties_handler.Grauers_metadata_properties_handler";
                        erd.SequenceNumber = 1000;
                        erd.Type = SPEventReceiverType.ItemCheckedIn;
                        erd.HostId = list.ID;
                        erd.HostType = SPEventHostType.List;
                        erd.Synchronization = SPEventReceiverSynchronization.Synchronous;
                        erd.Update();
                        #endregion

                        #region Checked out
                        erd = list.EventReceivers.Add();
                        erd.Assembly = Assembly.GetExecutingAssembly().FullName;
                        erd.Class = "Grauers_set_metadata_properties.Grauers_metadata_properties_handler.Grauers_metadata_properties_handler";
                        erd.SequenceNumber = 1000;
                        erd.Type = SPEventReceiverType.ItemCheckedOut;
                        erd.HostId = list.ID;
                        erd.HostType = SPEventHostType.List;
                        erd.Synchronization = SPEventReceiverSynchronization.Synchronous;
                        erd.Update();
                        #endregion

                        #region UnChecked out
                        erd = list.EventReceivers.Add();
                        erd.Assembly = Assembly.GetExecutingAssembly().FullName;
                        erd.Class = "Grauers_set_metadata_properties.Grauers_metadata_properties_handler.Grauers_metadata_properties_handler";
                        erd.SequenceNumber = 1000;
                        erd.Type = SPEventReceiverType.ItemUncheckedOut;
                        erd.HostId = list.ID;
                        erd.HostType = SPEventHostType.List;
                        erd.Synchronization = SPEventReceiverSynchronization.Synchronous;
                        erd.Update();
                        #endregion

                        list.Update();
                    }
                }
                DocumentPropertyBusinessLayer.Save(dpi);
                bindRepeater();
            }            
            #endregion

        }

        protected void updateImageButton_Click(object sender, EventArgs e)
        {            
            // Get all dpi
            List<DocumentPropertyItem> dpiList = DocumentPropertyBusinessLayer.GetAll();            

            // Try to find by library
            DocumentPropertyItem dpiFind = dpiList.FindLast(x => x.Library == DocumentsDropDownList.SelectedValue);

            dpiFind.Library = DocumentsDropDownList.SelectedValue;
            dpiFind.Issue = IssueDropDownList.SelectedValue;
            dpiFind.ApprovedBy = ApprovedByDropDownList.SelectedValue;
            dpiFind.ApprovedDate = ApprovedDateDropDownList.SelectedValue;

            DocumentPropertyBusinessLayer.Update(dpiList);

            cancelImageButton.Visible = false;
            updateImageButton.Visible = false;
            addImageButton.Visible = true;
            bindRepeater();
        }
        protected void cancelImageButton_Click(object sender, EventArgs e)
        {            
            cancelImageButton.Visible = false;
            updateImageButton.Visible = false;
            addImageButton.Visible = true;
        }
        
        protected void DocumentsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DocumentPropertyItem dpi = (DocumentPropertyItem)e.Item.DataItem;

                // Find Controls
                Label DocumentLabel = (Label)e.Item.FindControl("DocumentLabel");
                Label IssueLabel = (Label)e.Item.FindControl("IssueLabel");
                Label ApprovedByLabel = (Label)e.Item.FindControl("ApprovedByLabel");
                Label ApprovedDateLabel = (Label)e.Item.FindControl("ApprovedDateLabel");
                ImageButton deleteImageButton = (ImageButton)e.Item.FindControl("deleteImageButton");
                ImageButton editImageButton = (ImageButton)e.Item.FindControl("editImageButton");
                HtmlAnchor linkLibraryA = (HtmlAnchor)e.Item.FindControl("linkLibraryA");

                // Set Controls
                DocumentLabel.Text = dpi.Library;
                IssueLabel.Text = dpi.Issue;
                ApprovedByLabel.Text = dpi.ApprovedBy;
                ApprovedDateLabel.Text = dpi.ApprovedDate;
                deleteImageButton.CommandArgument = e.Item.ItemIndex.ToString();
                editImageButton.CommandArgument = e.Item.ItemIndex.ToString();
                deleteImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/Grauers/delete.png";
                editImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/Grauers/edit.png";

                // Get list
                SPList list = SPContext.Current.Web.Lists[dpi.Library];
                linkLibraryA.HRef = SPContext.Current.Site.Url +"/" +list.RootFolder.Url;


            }
        }
        protected void editImagButton_Click(object sender, EventArgs e)
        { 
            // get selected index
            int selectedIndex = int.Parse(((ImageButton)sender).CommandArgument.ToString());            

            // get dpi by index
            DocumentPropertyItem dpi = DocumentPropertyBusinessLayer.GetBy_Index(selectedIndex, SPContext.Current.Web);

            // set selected values dropdownlist
            Dictionary<DropDownList, string> dropDownDictonary = new Dictionary<DropDownList, string>();
            
            dropDownDictonary.Add(DocumentsDropDownList, dpi.Library);
            dropDownDictonary.Add(IssueDropDownList, dpi.Issue);
            dropDownDictonary.Add(ApprovedByDropDownList, dpi.ApprovedBy);
            dropDownDictonary.Add(ApprovedDateDropDownList, dpi.ApprovedDate);
            bindMetadata(dpi.Library);

            setSelectedValuesByDPI(dpi, dropDownDictonary);

            cancelImageButton.Visible = true;
            updateImageButton.Visible = true;
            addImageButton.Visible = false;            

        }

        private void setSelectedValuesByDPI(DocumentPropertyItem dpi, Dictionary<DropDownList,string> dropDownDictonary)
        {
            List<DropDownList> ddlList = new List<DropDownList>(dropDownDictonary.Keys);
            foreach (DropDownList ddl in ddlList)
            {
                //string selectedValueString = dropDownDictonary.
                ListItem item = ddl.Items.FindByText(dropDownDictonary[ddl]);
                if (item != null)
                {
                    ddl.SelectedIndex = -1;
                    item.Selected = true;
                }
            }

        }
        protected void deleteImageButton_Click(object sender, EventArgs e)
        {
            try
            {
                List<DocumentPropertyItem> dpiList = DocumentPropertyBusinessLayer.GetAll();

                int index = -1;
                index = int.Parse(((ImageButton)sender).CommandArgument);
                if (index != -1)
                {
                    DocumentPropertyItem dpi = dpiList[index];
                    General.RemoveEventReceiver(dpi.Library);

                    dpiList.RemoveAt(index);
                    DocumentPropertyBusinessLayer.Update(dpiList);
                    
                    bindRepeater();
                }
            }
            catch (Exception ex)
            {

            }            
        }
        
        protected void DocumentsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            bindMetadata(DocumentsDropDownList.SelectedValue);
        }

        
        #region private
        #region bindings()
        private void bindRepeater()
        {
            DocumentsRepeater.DataSource = DocumentPropertyBusinessLayer.GetAll();
            DocumentsRepeater.DataBind();
        }
        private void bindDocumentLibraries()
        {
            // Only get document libraries                        
            DocumentsDropDownList.DataSource = SPContext.Current.Web.GetListsOfType(SPBaseType.DocumentLibrary);
            DocumentsDropDownList.DataBind();
        }
        
        private void bindMetadata(string libraryName)
        {            
            SPList list = SPContext.Current.Web.Lists[libraryName];
            ArrayList al = new ArrayList();
            al.Add("--Don't use--");
            foreach (SPField field in list.Fields)
            { 
                string fieldTypeClass = field.FieldTypeDefinition.FieldTypeClass;
                // Only add custom fields with text type
                if ((!SPBuiltInFieldId.Contains(field.Id) && field.Type == SPFieldType.Text || field.Type == SPFieldType.DateTime || field.Type == SPFieldType.User) && !field.FromBaseType &&!field.ReadOnlyField &&!field.Sealed)
                {
                    al.Add(field.Title);
                }
            }

            #region Bind dropdowns
            IssueDropDownList.DataSource = al;
            IssueDropDownList.DataBind();

            ApprovedByDropDownList.DataSource = al;
            ApprovedByDropDownList.DataBind();

            ApprovedDateDropDownList.DataSource = al;
            ApprovedDateDropDownList.DataBind();
            #endregion

            #region Selectet DropDowns
            // Try to set selected values dropdown
            ListItem item = IssueDropDownList.Items.FindByText("Issue");
            if (item != null)
                item.Selected = true;

            ListItem itemApprovedBy = ApprovedByDropDownList.Items.FindByText("Approved by");
            if (itemApprovedBy != null)
                itemApprovedBy.Selected = true;

            ListItem itemApprovedDate = ApprovedDateDropDownList.Items.FindByText("Approved date");
            if (itemApprovedDate != null)
                itemApprovedDate.Selected = true;
            #endregion

            cancelImageButton.Visible = false;
            updateImageButton.Visible = false;
            addImageButton.Visible = true;

        }
        #endregion


        #endregion
    }
}


